
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <vector>
#include <cstdlib>
#include <fstream>
#include <cstring>
#include <sqlite3.h>

using namespace std;

class Database
{
public:
        Database(char* filename);
        ~Database();
        
        bool open(char* filename);
        vector<vector<string> > query(char* query);
        int getFail() {return fail;}
        void close();
        
private:
        sqlite3 *database;
        int fail;
};


Database::Database(char* filename)
{
        database = NULL;
        fail = 0;
        open(filename);
}

Database::~Database()
{
}

bool Database::open(char* filename)
{
        if(sqlite3_open(filename, &database) == SQLITE_OK)
                return true;
                
        return false;   
}

vector<vector<string> > Database::query(char* query)
{  
     sqlite3_stmt *statement;
     vector<vector<string> > results;
        
       if(sqlite3_prepare_v2(database, query, -1, &statement, 0) == SQLITE_OK)
        {
               int cols = sqlite3_column_count(statement);
               int result = 0;
                while(true)
                {
                        result = sqlite3_step(statement);
                        
                       if(result == SQLITE_ROW)
                        {
                                vector<string> values;
                                for(int col = 0; col < cols; col++)
                               {
                                    //std::string val;
                                    string s;
                                    char *ptr = (char*)sqlite3_column_text(statement, col);
                                    if(ptr)
                                    {
                                        s = ptr;
                                    }
                                    else s = "";
                                    
                                    values.push_back(s);
                                    
                                }
                              results.push_back(values);
                        }
                        else
                        {
                                break;   
                        }
                }
           
                sqlite3_finalize(statement);
        }
        
        string error = sqlite3_errmsg(database);
        if(error != "not an error"){
            fail = 1;
            cout << query << " " << error << endl;
        }
        return results;  
}



void Database::close()
{
        sqlite3_close(database);   
}